<#macro scriptMacro>
  <script>
    var uploadFiles = new Array();
    layui.use(['form', 'upload'], function () {
      let upload = layui.upload,
          $ = layui.jquery;
      //多图片上传
      upload.render({
        elem: '#selectBtn'
        , multiple: true
        , accept: 'images'
        , exts: 'jpg|png|jpeg|gif'
        , drag: true
        , auto: false
        , size: 10240 //限制文件大小，单位 KB
        , choose: function (obj) {
          //预读本地文件示例，不支持ie8
          obj.preview(function (index, file, result) {
            var sizeStr = getFileSize(file.size);
            $('#imgPreview').append('<div class="upload-preview-item"><a onclick="viewPics()">' +
                '<img src="' + result + '" alt="' + file.name + '"/></a>' +
                '<div class="preview-img-info"><span>' + sizeStr + '</span><i class="fa fa-times" onclick="removeImg(this)" data-img-name="' + file.name + '"></i></div>' +
                '</div>');
            uploadFiles.push(file);
          });
        }
      });
    })

    function getFileSize(size) {
      let unit = "KB";
      let s = size / 1024;
      if (s >= 1024) {
        unit = "MB";
        s = s / 1024
      }
      return s.toFixed(2) + unit;
    }

    function removeImg(target) {
      let $ = layui.jquery;
      let fileName = $(target).attr("data-img-name");
      $(target).parents(".upload-preview-item").remove();
      for (let fileIndex in uploadFiles) {
        if (uploadFiles[fileIndex].name === fileName) {
          uploadFiles.splice(fileIndex, 1);
          return;
        }
      }
    }

    function uploadImgs() {
      let $ = layui.jquery;
      let formData = new FormData();
      formData.append("emoticonCode", $("select[name=code]").val())
      if (uploadFiles && uploadFiles.length >= 1) {
        for (let imgIndex in uploadFiles) {
          formData.append("files", uploadFiles[imgIndex]);
        }
        let opts = {
          url: "${request.contextPath}/emoticon/doUpload"
          , type: 'post' //统一采用 post 上传
          , data: formData
          , contentType: false
          , processData: false
          , ayync: true
          //成功回调
          , success: function (result) {
            layMsg(result.msg);
            if (result.success) {
              setTimeout(function () {
                window.location.reload();
              }, 2000);
            }
          }
          //异常回调
          , error: function () {

          }
        };
        $.ajax(opts);
      } else {
        layMsg("请添加需要上传的图片！");
      }
    }

    function viewPics() {
      //调用示例
      layui.layer.photos({
        photos: '#imgPreview'
        , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
      });
    }

    layui.use(['form', 'table'], function () {
      var $ = layui.jquery,
          form = layui.form,
          table = layui.table;

      table.render({
        elem: '#emoticonTable',
        request: {
          pageName: 'current',
          limitName: 'size'
        },
        where: {
          code: $('select[name=code]').val()
        },
        url: '${request.contextPath}/emoticon/page',
        method: 'POST',
        cols: [[
          {field: 'id', width: 80, title: 'ID'},
          {field: 'emoticonFromDesc', width: 80, title: '分类'},
          {
            title: '状态',
            width: 100,
            templet: '#usableTpl'
          },
          {width: 150, title: '预览', templet: '#imgPreviewTpl'},
          //{width: 150, title: '预览', templet: '<div><img src="{{d.imgUrl}}"/></div>'}, // 这么写会有BUG不知道为啥 layui会直接拿占位符{{d.imgUrl}}去找图片
          //{field: 'imgUrl', width: 550, title: '地址'},
          {field: 'name', width: 150, title: '名称'},
          {
            title: '创建时间',
            width: 180,
            sort: true,
            templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'
          },
          {
            title: '修改时间',
            width: 180,
            sort: true,
            templet: '<div>{{ layui.util.toDateString(d.modifyTime, "yyyy-MM-dd HH:mm:ss") }}</div>'
          },
          {title: '操作', toolbar: '#currentTableBar', align: "center"},
        ]],
        limits: [10, 15, 20, 25, 50, 100],
        limit: 10,
        page: true,
        skin: 'line',
        parseData: function (res) {
          var page = res.data;
          if (page) {
            currentPage = page.current;
            return {
              "code": res.code,
              "msg": res.msg,
              "count": page.total,
              "data": page.records
            }
          } else {
            return {
              "code": res.code,
              "msg": res.msg
            }
          }
        },
      });

      $("#search-btn").on('click', function () {
        reloadTable(1);
      })

      table.on('tool(emoticonTableFilter)', function (obj) {
        var data = obj.data;
        if (obj.event === 'delete') {
          layer.confirm('真的删除行么', function (index) {
            $.post("${request.contextPath}/emoticon/delete", {
              id: data.id
            }, function (result) {
              layMsg(result.msg);
              if (result.success) {
                layer.close(index);
                reloadTable();
              }
            })
          });
        } else if (obj.event === 'active' || obj.event === 'forbid') {
          $.post("${request.contextPath}/emoticon/toggleUsable", {
            id: data.id
          }, function (result) {
            layMsg(result.msg);
            if (result.success) {
              reloadTable();
            }
          })
        } else if (obj.event === 'modify') {
          layer.prompt(function (value, index) {
            $.post("${request.contextPath}/emoticon/modifyName", {
              id: data.id,
              name: value
            }, function (result) {
              layMsg(result.msg);
              layer.close(index);
              if (result.success) {
                reloadTable();
              }
            })
          })
        }
      });
    });

    var currentPage = 1;

    function reloadTable(page) {
      layui.use('table', function () {
        var $ = layui.jquery, table = layui.table;
        //执行搜索重载
        table.reload('emoticonTable', {
          page: {
            curr: page ? page : currentPage
          },
          where: {
            code: $('select[name=code]').val()
          }
        }, true);
      })
    }

  </script>
</#macro>
<@zlt.page title="表情列表" scriptMacro=scriptMacro>
  <body>
  <div class="layuimini-container">
    <div class="layuimini-main">
      <div class="layui-upload p-2">
        <div class="layui-upload-drag d-block" id="selectBtn" style="display: block">
          <i class="layui-icon"></i>
          <p>点击多图上传，或将文件拖拽到此处</p>
        </div>
        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
          预览图：
          <div class="layui-upload-list upload-preview-box" id="imgPreview"></div>
        </blockquote>
      </div>
      <fieldset class="table-search-fieldset">
        <legend>搜索表情</legend>
        <div class="layui-form" style="margin: 10px 10px 10px 10px">
          <div class="layui-form-item">
            <div class="layui-inline">
              <label class="layui-form-label">分类</label>
              <div class="layui-input-inline">
                <select name="code">
                  <option value="">请选择分类</option>
                    <#list emoticonFroms as from>
                      <option value="${from.code}">${from.desc}</option>
                    </#list>
                </select>
              </div>
            </div>
            <div class="layui-inline">
              <button type="button" id="search-btn" class="layui-btn layui-btn-primary"><i class="layui-icon"></i> 搜 索
              </button>
              <button type="button" class="layui-btn" onclick="uploadImgs()"><i class="fas fa-upload"></i> 上 传
              </button>
            </div>
          </div>
        </div>
      </fieldset>
      <table class="layui-hide" id="emoticonTable" lay-filter="emoticonTableFilter"></table>
    </div>
  </div>
  </body>

  <script type="text/html" id="currentTableBar">
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="modify">设置名称</a>
    {{# if(!d.isUsable){ }}
    <a class="layui-btn layui-btn-xs" lay-event="active">启用</a>
    {{# } else { }}
    <a class="layui-btn layui-btn-xs layui-btn-warm" lay-event="forbid">禁用</a>
    {{# } }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
  </script>

  <script type="text/html" id="usableTpl">
    {{# if(d.isUsable) { }}
      <span class="layui-badge layui-bg-normal">正常</span>
    {{# } else{ }}
      <span class="layui-badge layui-bg-red">禁用</span>
    {{# } }}
  </script>

    <script type="text/html" id="imgPreviewTpl">
      <img src="{{d.imgUrl}}"/>
    </script>
</@zlt.page>